package com.xcesys.extras.remoting.schedule.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.jws.WebService;

import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.Trigger.TriggerState;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.xcesys.extras.core.exception.ApplicationException;
import com.xcesys.extras.core.exception.SystemException;
import com.xcesys.extras.core.job.AbstractQuartzJobBean;
import com.xcesys.extras.core.job.service.QuartzSchedulerService;
import com.xcesys.extras.core.util.Assert;
import com.xcesys.extras.core.util.StringUtil;
import com.xcesys.extras.dataobject.NameValuePair;
import com.xcesys.extras.dataobject.schedule.JobDataObject;
import com.xcesys.extras.dataobject.schedule.JobLog;
import com.xcesys.extras.dataobject.schedule.TriggerDataObject;
import com.xcesys.extras.model.TlJobLog;
import com.xcesys.extras.remoting.BaseRemotingServiceImpl;
import com.xcesys.extras.remoting.IDataObjectHelper;
import com.xcesys.extras.remoting.schedule.RScheduleManagerService;
import com.xcesys.extras.system.service.TlJobLogService;

/**
 * Schedule管理服务类
 * 
 * @author LiangShenFan
 */
@Service("RScheduleManagerService")
@WebService(endpointInterface = "com.xcesys.extras.remoting.schedule.RScheduleManagerService")
public class RScheduleManagerServiceImpl extends BaseRemotingServiceImpl
		implements RScheduleManagerService, ApplicationContextAware {
	private ApplicationContext applicationContext;

	@Autowired(required = false)
	private QuartzSchedulerService schedulerService;

	@Autowired
	private TlJobLogService tlJobLogService;

	@Autowired(required = false)
	@Qualifier("dozerDataObjectHelper")
	IDataObjectHelper dataHelper = null;

	/**
	 * 构造方法
	 * 
	 * @throws SchedulerException
	 */
	public RScheduleManagerServiceImpl() {
	}

	@Override
	public void addOrUpdateJob(JobDataObject jobDataObject) {
		String jobName = jobDataObject.getJobName();
		String jobGroup = jobDataObject.getJobGroup();
		String jobClass = jobDataObject.getJobClass();
		try {
			NameValuePair[] jobParams = jobDataObject.getJobParams();
			JobDataMap jobDataMap = new JobDataMap();
			array2JobDataMap(jobDataMap, jobParams);
			JobDetail jobDetail = schedulerService.addJob(jobName, jobGroup,
					jobClass, jobDataObject.getJobDescription(), jobDataMap,
					true);
		} catch (SchedulerException e) {
			throw new SystemException("");
		}
	}

	@Override
	public TriggerDataObject addOrUpdateTrigger(TriggerDataObject object) {
		Assert.notNull(object);

		String jobName = object.getJobName();
		String jobGroup = object.getJobGroup();
		if (StringUtil.isNullOrBlank(jobGroup)) {
			jobGroup = Scheduler.DEFAULT_GROUP;
		}
		String jobClass = object.getJobClass();

		String triggerName = object.getName();
		String triggerGroup = object.getGroup();
		if (StringUtil.isNullOrBlank(triggerGroup)) {
			triggerGroup = Scheduler.DEFAULT_GROUP;
		}

		try {
			TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroup);

			// remove previous set triggers.
			Trigger oldTrigger = schedulerService.getTrigger(triggerKey);

			if (oldTrigger != null) {
				schedulerService.deleteTrigger(triggerKey);
				log.debug("Old trigger :" + triggerName + " in group:"
						+ triggerGroup + " found and unschedule it.");
			}

			JobKey jobKey = new JobKey(jobName, jobGroup);
			JobDetail jobDetail = schedulerService.getJob(jobKey);
			if (jobDetail == null) {
				// try to find job detail bean from spring container first.
				try {
					Object bean = applicationContext.getBean(jobName,
							JobDetail.class);
					if (bean != null && bean instanceof JobDetail) {
						jobDetail = (JobDetail) bean;
						log.debug("JobDetail bean:" + jobName
								+ " found in spring container.");
					}
				} catch (Exception e) {

				}
				if (jobDetail == null) {
					Class<? extends Job> clazz = (Class<? extends Job>) Class
							.forName(jobClass);
					jobDetail = JobBuilder.newJob(clazz)
							.withDescription(object.getDescription())
							.withIdentity(jobKey).build();
					log.debug("Created a new JobDetail bean:" + jobName
							+ " with class:" + jobClass + ".");
				}
				schedulerService.addJob(jobDetail, true);
			}

			// recreate new trigger.
			Trigger trigger = buildTrigger(object);
			array2JobDataMap(trigger.getJobDataMap(), object.getJobParams());

			Date time = schedulerService.rescheduleJob(triggerKey, trigger);
			schedulerService.pauseTrigger(triggerKey);
			object.setNextFireTime(time);
			TriggerState triggerState = schedulerService
					.getTriggerState(triggerKey);
			object.setTriggerStatus(TriggerDataObject.TriggerState
					.valueOf(triggerState.name()));
			object.setTriggerStatusName(schedulerService
					.getTriggerStateName(triggerKey));

		} catch (SchedulerException e) {
			throw newSystemException(e);
		} catch (ClassNotFoundException e) {
			throw new SystemException("SE0013", new String[] { e.getMessage() });
		} catch (Exception e) {
			throw newSystemException(e);
		}
		return object;

	}

	private void array2JobDataMap(JobDataMap map, NameValuePair[] ns) {
		if (ns != null) {
			for (NameValuePair np : ns) {
				map.put(np.getName(), np.getValue());
			}
		}
	}

	private Trigger buildTrigger(TriggerDataObject obj) {
		int trigerType = obj.getTriggerType();
		return TriggerBuilder
				.newTrigger()
				.withSchedule(
						SimpleScheduleBuilder.simpleSchedule()
								.withIntervalInMilliseconds(
										obj.getRepeatInterval()))
				.withDescription(obj.getDescription())
				.withIdentity(obj.getName(), obj.getGroup()).build();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.ewin.mes.service.schedule.ScheduleManagerService#
	 * checkSchedulerStatus()
	 */
	@Override
	public String checkStatus() {
		Scheduler scheduler = schedulerService.getScheduler();
		try {
			if (scheduler.isInStandbyMode()) {
				return "StandBy";
			} else if (scheduler.isShutdown()) {
				return "Shutdown";
			} else if (scheduler.isStarted()) {
				return "Started";
			}
			return "";
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
	}

	/**
	 * <p>
	 * Delete the identified <code>Job</code> from the Scheduler - and any
	 * associated <code>Trigger</code>s.
	 * </p>
	 */
	@Override
	public void deleteJob(String jobName, String groupName) {
		try {
			schedulerService.deleteJob(new JobKey(jobName, groupName));
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
	}

	@Override
	public void deleteTrigger(String triggerName, String triggerGroup,
			String jobName) {
		try {
			schedulerService.deleteTrigger(new TriggerKey(triggerName,
					triggerGroup));
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<String> getAllJobGroups() {
		try {
			return schedulerService.getAllJobGroups();
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
	}

	@Override
	public List<String> getAllJobNamesFromQuartz(String jobGroup) {
		try {
			List<String> names = new ArrayList<String>();
			List<JobKey> keys = schedulerService.getAllJobName(jobGroup);
			for (JobKey jobKey : keys) {
				names.add(jobKey.getName());
			}
			return names;
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<String> getAllJobNamesFromSpring(String jobGroup) {
		String[] jobNames = applicationContext
				.getBeanNamesForType(JobDetail.class);
		if (jobGroup == null || "".equals(jobGroup)) {
			return Arrays.asList(jobNames);
		}
		List<String> names = new ArrayList<String>();
		for (String name : jobNames) {
			try {
				JobDetail bean = applicationContext.getBean(name,
						JobDetail.class);
				if (jobGroup.equals(bean.getKey().getGroup())) {
					names.add(name);
				}
			} catch (Exception e) {

			}
		}
		return names;
	}

	@Override
	public List<JobDataObject> getAllJobs(List<String> jobGroups) {
		try {
			if (jobGroups == null) {
				jobGroups = getAllJobGroups();
			}
			List<JobDataObject> jobs = new ArrayList<JobDataObject>();
			List<JobDetail> allJobs = schedulerService.getAllJobs(jobGroups);
			for (JobDetail jobDetail : allJobs) {
				JobDataObject job = new JobDataObject();
				try {
					job.setJobName(jobDetail.getKey().getName());
					job.setJobGroup(jobDetail.getKey().getGroup());
					job.setJobClass(jobDetail.getJobClass().getName());
					job.setJobDescription(jobDetail.getDescription());
					job.setJobParams(jobDataMap2Array(jobDetail.getJobDataMap()));
				} catch (Exception e) {
					job.setJobDescription("**[!读取任务信息异常!]**");
				}
				jobs.add(job);
			}
			return jobs;
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取所有的trigger列表信息
	 * 
	 * @return
	 */
	@Override
	public Collection<TriggerDataObject> getAllTrigers(List<String> groups) {
		if (schedulerService == null) {
			throw new ApplicationException("AEA0157", "");
			// AEA0157 ="调度程序没有启动!无法进行调度任务的获取!"
		}
		Collection<TriggerDataObject> resultCollection = new ArrayList<TriggerDataObject>();
		try {
			if (groups == null || groups.isEmpty()) {
				groups = schedulerService.getAllTriggerGroups();
			}
			for (String gn : groups) {
				List<Trigger> triggers = schedulerService.getAllTriggers(gn);

				for (Trigger trigger : triggers) {
					TriggerKey key = trigger.getKey();

					// if (trigger == null) {
					// log.warn("No trigger found according to trigger name: "
					// + key);
					// continue;
					// }
					log.debug("Retrieving trigger [" + key + "] information...");
					JobKey jobKey = trigger.getJobKey();

					String jobDescription = null;
					String jobClass = null;
					JobDetail job = null;
					try {
						job = schedulerService.getJob(jobKey);
					} catch (Exception e) {
						log.warn("Can not retrieve job detail from quartz.", e);
					}
					if (job != null) {
						jobDescription = job.getDescription();
						jobClass = job.getJobClass().getName();
					}
					TriggerState triggerState = schedulerService
							.getTriggerState(key);
					String triggerStateName = schedulerService
							.getTriggerStateName(key);
					Long ellapse = (Long) trigger.getJobDataMap().get(
							AbstractQuartzJobBean.JOB_LAST_TIME_ELLAPSE);

					// trigger properties.
					TriggerDataObject triggerDataObject = new TriggerDataObject();
					triggerDataObject.setName(key.getName());
					triggerDataObject.setGroup(key.getGroup());
					triggerDataObject.setDescription(trigger.getDescription());
					triggerDataObject
							.setTriggerStatus(TriggerDataObject.TriggerState
									.valueOf(triggerState.name()));
					triggerDataObject.setTriggerStatusName(triggerStateName);

					// job details.
					triggerDataObject.setJobName(jobKey.getName());
					triggerDataObject.setJobGroup(jobKey.getGroup());
					triggerDataObject.setJobDescription(jobDescription);
					triggerDataObject.setJobClass(jobClass);

					triggerDataObject.setMayFireAgain(trigger.mayFireAgain());
					triggerDataObject.setPreviousFireTime(trigger
							.getPreviousFireTime());
					triggerDataObject
							.setNextFireTime(trigger.getNextFireTime());
					triggerDataObject.setPrevElapse(ellapse);
					JobDataMap map = trigger.getJobDataMap();
					if ((map == null || map.isEmpty()) && job != null) {
						map = job.getJobDataMap();
					}
					triggerDataObject.setJobParams(jobDataMap2Array(map));

					if (trigger instanceof SimpleTrigger) {
						SimpleTrigger simpleTrigger = (SimpleTrigger) trigger;
						triggerDataObject
								.setTriggerType(TriggerDataObject.TRIGGER_TYPE_SIMPLE);
						triggerDataObject.setStartTime(simpleTrigger
								.getStartTime());
						triggerDataObject
								.setEndTime(simpleTrigger.getEndTime());
						triggerDataObject.setRepeatCount(simpleTrigger
								.getRepeatCount());
						triggerDataObject.setRepeatInterval(simpleTrigger
								.getRepeatInterval());
					} else if (trigger instanceof CronTrigger) {
						CronTrigger cronTrigger = (CronTrigger) trigger;
						triggerDataObject
								.setTriggerType(TriggerDataObject.TRIGGER_TYPE_CRON);
						triggerDataObject.setCronExpression(cronTrigger
								.getCronExpression());
					}
					resultCollection.add(triggerDataObject);
					log.debug("Retrieving trigger [" + key
							+ "] information success!");
				}
			}
			// }
		} catch (SchedulerException e) {
			e.printStackTrace();
			throw new ApplicationException("AEA0158", new String[] {},
					e.getCause());

		}

		return resultCollection;
	}

	@Override
	public List<String> getAllTriggerGroups() {
		try {
			return schedulerService.getAllTriggerGroups();
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
	}

	@Override
	public JobDataObject getJobFromQuartz(String jobName) {
		List<String> jobGroups = null;

		try {
			jobGroups = schedulerService.getAllJobGroups();
		} catch (SchedulerException e1) {
			e1.printStackTrace();
		}
		if (jobGroups != null) {
			for (String jobGroup : jobGroups) {
				JobKey key = new JobKey(jobName, jobGroup);
				JobDetail job = null;
				try {
					job = schedulerService.getJob(key);
				} catch (SchedulerException e) {
					e.printStackTrace();
				}
				if (job != null) {
					JobDataObject jobDataObject = new JobDataObject();
					jobDataObject.setJobClass(job.getJobClass().getName());
					jobDataObject.setJobDescription(job.getDescription());
					jobDataObject.setJobGroup(jobGroup);
					jobDataObject.setJobName(jobName);
					jobDataObject.setJobParams(jobDataMap2Array(job
							.getJobDataMap()));
					return jobDataObject;
				}
			}
		}
		return null;
	}

	@Override
	public JobDataObject getJobFromSpring(String beanName) {
		Object bean = applicationContext.getBean(beanName);
		JobDataObject object = null;
		if (bean instanceof JobDetail) {
			JobDetail jobDetail = (JobDetail) bean;
			object = new JobDataObject();
			object.setJobName(jobDetail.getKey().getName());
			object.setJobClass(jobDetail.getJobClass().getName());
			object.setJobDescription(jobDetail.getDescription());
			object.setJobGroup(jobDetail.getKey().getGroup());
			JobDataMap map = jobDetail.getJobDataMap();
			object.setJobParams(jobDataMap2Array(map));
		}
		return object;
	}

	@Override
	public Collection<JobLog> getJobLogs(String triggerName, String jobName,
			Date lastDate) {
		List<TlJobLog> tlSysJobLogs = tlJobLogService.getJobLogs(triggerName,
				jobName, lastDate);
		return dataHelper.copyProperties(JobLog.class, tlSysJobLogs);
	}

	/**
	 * 获取指定的Trigger信息
	 * 
	 * @param trigerName
	 *            trigger名称
	 * @param trigerGName
	 *            trigger组信息，可以为空
	 * @return
	 */
	public TriggerDataObject getTrigger(String trigerName, String trigerGName) {
		if (schedulerService == null) {
			throw new ApplicationException("AEA0157", "");
			// AEA0157 ="调度程序没有启动!无法进行调度任务的获取!"
		}
		Trigger trigger;
		try {
			trigger = schedulerService.getTrigger(new TriggerKey(trigerName,
					trigerGName));

			if (trigger != null) {
				if (trigger instanceof SimpleTrigger) {
					SimpleTrigger simpleTrigger = (SimpleTrigger) trigger;
					TriggerDataObject triggerDataObject = new TriggerDataObject();
					triggerDataObject.setDescription(simpleTrigger
							.getDescription());
					triggerDataObject.setGroup(simpleTrigger.getKey()
							.getGroup());
					triggerDataObject.setJobGroup(simpleTrigger.getJobKey()
							.getGroup());
					triggerDataObject.setJobName(simpleTrigger.getJobKey()
							.getName());
					triggerDataObject.setJobDescription(simpleTrigger
							.getDescription());
					triggerDataObject.setMayFireAgain(simpleTrigger
							.mayFireAgain());
					triggerDataObject.setName(simpleTrigger.getKey().getName());
					triggerDataObject.setPreviousFireTime(simpleTrigger
							.getPreviousFireTime());
					triggerDataObject.setNextFireTime(simpleTrigger
							.getNextFireTime());
					triggerDataObject.setRepeatInterval(simpleTrigger
							.getRepeatInterval());
					// resultCollection.add(triggerDataObject);
					return triggerDataObject;
				} else if (trigger instanceof CronTrigger) {
					CronTrigger simpleTrigger = (CronTrigger) trigger;
					TriggerDataObject triggerDataObject = new TriggerDataObject();
					triggerDataObject.setDescription(simpleTrigger
							.getDescription());
					triggerDataObject.setGroup(simpleTrigger.getKey()
							.getGroup());
					triggerDataObject.setJobGroup(simpleTrigger.getJobKey()
							.getGroup());
					triggerDataObject.setJobName(simpleTrigger.getJobKey()
							.getName());
					triggerDataObject.setJobDescription(simpleTrigger
							.getDescription());
					triggerDataObject.setMayFireAgain(simpleTrigger
							.mayFireAgain());
					triggerDataObject.setName(simpleTrigger.getKey().getName());
					triggerDataObject.setPreviousFireTime(simpleTrigger
							.getPreviousFireTime());
					triggerDataObject.setNextFireTime(simpleTrigger
							.getNextFireTime());
					triggerDataObject.setCronExpression(simpleTrigger
							.getCronExpression());
					// resultCollection.add(triggerDataObject);
					return triggerDataObject;
				}
			}
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
		return null;

	}

	private NameValuePair[] jobDataMap2Array(JobDataMap map) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if (map != null && !map.isEmpty()) {
			for (Object key : map.keySet()) {
				Object value = map.get(key);
				params.add(new NameValuePair(key.toString(),
						value == null ? null : value.toString()));
			}
		}
		return params.toArray(new NameValuePair[] {});
	}

	private String jobDataMapToString(JobDataMap map) {
		StringBuffer sb = new StringBuffer();
		if (map != null && !map.isEmpty()) {
			for (Object key : map.keySet()) {
				Object value = map.get(key);
				String str = "," + key.toString() + "="
						+ (value == null ? "" : value.toString());
				if (sb.length() + str.length() > 1000) {
					log.warn("TmSysJobConfig中参数字符串长度超过允许最大长度1000字节，部分参数被忽略。");
					break;
				}
				sb.append(str);
			}
			if (sb.length() > 0) {
				sb.deleteCharAt(0);
			}
			return sb.toString();
		}
		return null;
	}

	/**
	 * New a system exception from SchedulerException.
	 * 
	 * @param e
	 *            SchedulerException
	 * @return SystemException.
	 */
	private SystemException newSystemException(Exception e) {
		if (e instanceof SchedulerException) {
			return new SystemException(""
					+ ((SchedulerException) e).getMessage(), null, e.getCause());
		}
		return new SystemException(e.getMessage(), null, e);
	}

	@Override
	public void pauseAllTriggers() {
		Scheduler scheduler = schedulerService.getScheduler();
		try {
			scheduler.pauseAll();
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
	}

	/**
	 * <p>
	 * Pause the <code>{@link Trigger}</code> with the given name.
	 * </p>
	 * 
	 * @see #resumeTrigger(String, String)
	 */
	@Override
	public void pauseTrigger(List<TriggerDataObject> triggers) {
		for (TriggerDataObject triggerDataObject : triggers) {
			String groupName = triggerDataObject.getGroup();
			if (groupName == null || "".equals(groupName)) {
				groupName = Scheduler.DEFAULT_GROUP;
			}
			String triggerName = triggerDataObject.getName();
			if (log.isInfoEnabled()) {
				log.debug("Paused trigger name: " + triggerName
						+ ", and related job name:"
						+ triggerDataObject.getJobName());
			}
			try {
				schedulerService.pauseTrigger(new TriggerKey(triggerName,
						groupName));
			} catch (SchedulerException e) {
				throw newSystemException(e);
			}
		}
	}

	/**
	 * <p>
	 * Remove (delete) the <code>{@link org.quartz.Trigger}</code> with the
	 * given name, and store the new given one - which must be associated with
	 * the same job (the new trigger must have the job name & group specified) -
	 * however, the new trigger need not have the same name as the old trigger.
	 * </p>
	 * 
	 * @param triggers
	 *            The new <code>Trigger</code> to be stored.
	 */
	@Override
	public void rescheduleJob(List<TriggerDataObject> triggerDataObjects) {
		if (schedulerService == null) {
			throw new ApplicationException("AEA0157", "");
			// AEA0157 ="调度程序没有启动!无法进行调度任务的获取!"
		}
		for (TriggerDataObject triggerDataObject : triggerDataObjects) {
			String groupName = triggerDataObject.getGroup();
			if (groupName == null || "".equals(groupName)) {
				groupName = Scheduler.DEFAULT_GROUP;
			}
			String triggerName = triggerDataObject.getName();
			Trigger trigger;
			try {
				trigger = schedulerService.getTrigger(new TriggerKey(
						triggerName, groupName));

				if (trigger != null) {
					// if (trigger instanceof SimpleTrigger) {
					// SimpleTrigger newTrigger = (SimpleTrigger) trigger;
					// TriggerDataObject simpleTriggerDataObject =
					// triggerDataObject;
					// newTrigger.setRepeatInterval(simpleTriggerDataObject
					// .getRepeatInterval());
					// schedulerService.rescheduleJob(triggerName, groupName,
					// newTrigger);
					// } else if (trigger instanceof CronTrigger) {
					// CronTrigger newTrigger = (CronTrigger) trigger;
					// TriggerDataObject cronTriggerDataObject =
					// triggerDataObject;
					// try {
					// newTrigger.setCronExpression(cronTriggerDataObject
					// .getCronExpression());
					// } catch (ParseException e) {
					// e.printStackTrace();
					// throw new ApplicationException(e.getMessage(),
					// null, e);
					// }
					// schedulerService.rescheduleJob(triggerName, groupName,
					// newTrigger);
					//
					// }
				}
			} catch (SchedulerException e) {
				throw newSystemException(e);
			}
		}
	}

	@Override
	public void resumeAllTriggers() {
		Scheduler scheduler = schedulerService.getScheduler();
		try {
			scheduler.resumeAll();
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
	}

	/**
	 * 恢复一个trigger
	 * 
	 * @param triggerName
	 *            trigger名称
	 * @param groupName
	 *            组名称
	 */
	@Override
	public void resumeTrigger(String triggerName, String groupName) {
		try {
			schedulerService.resumeTrigger(new TriggerKey(triggerName,
					groupName));
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
	}

	/**
	 * <p>
	 * Schedule the given <code>{@link org.quartz.Trigger}</code> with the
	 * <code>Job</code> identified by the <code>Trigger</code>'s settings.
	 * </p>
	 */
	@Override
	public Date scheduleJobByTriger(TriggerDataObject tdo) {
		Trigger trigger;
		try {
			TriggerKey key = new TriggerKey(tdo.getName(), tdo.getGroup());
			trigger = schedulerService.getTrigger(key);
			if (trigger instanceof SimpleTrigger) {
				trigger = TriggerBuilder
						.newTrigger()
						.withIdentity(key)
						.withSchedule(
								SimpleScheduleBuilder
										.simpleSchedule()
										.withIntervalInMilliseconds(
												tdo.getRepeatInterval())
										.withRepeatCount(tdo.getRepeatCount()))
						.build();
				// resultCollection.add(triggerDataObject);
				return schedulerService.scheduleJob(trigger);
			} else if (trigger instanceof CronTrigger) {
				return schedulerService.scheduleJob(trigger);

			}
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
		return null;

	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

	/**
	 * <p>
	 * Halts the <code>Scheduler</code>'s firing of
	 * <code>{@link Trigger}s</code>, and cleans up all resources associated
	 * with the Scheduler. Equivalent to <code>shutdown(false)</code>.
	 * </p>
	 * 
	 * <p>
	 * The scheduler cannot be re-started.
	 * </p>
	 * 
	 * @see #shutdown(boolean)
	 */
	@Override
	public void shutdown() {
		try {
			Scheduler scheduler = schedulerService.getScheduler();
			if (!scheduler.isInStandbyMode()) {
				scheduler.standby();
				scheduler.pauseAll();
				log.info("Scheduler [" + scheduler.getSchedulerInstanceId()
						+ "] turned to standby mode.");
			} else {
				log.info("Scheduler [" + scheduler.getSchedulerInstanceId()
						+ "] already in standby mode.");
			}
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
	}

	/**
	 * <p>
	 * Starts the <code>Scheduler</code>'s threads that fire
	 * <code>{@link Trigger}s</code>. When a scheduler is first created it is in
	 * "stand-by" mode, and will not fire triggers. The scheduler can also be
	 * put into stand-by mode by calling the <code>standby()</code> method.
	 * </p>
	 * 
	 * <p>
	 * The misfire/recovery process will be started, if it is the initial call
	 * to this method on this scheduler instance.
	 * </p>
	 * 
	 * @see #standby
	 * @see #shutdown
	 */
	@Override
	public void start() {
		try {
			Scheduler scheduler = schedulerService.getScheduler();
			if (scheduler.isInStandbyMode() || scheduler.isShutdown()) {
				scheduler.start();
				scheduler.resumeAll();
				log.info("Scheduler [" + scheduler.getSchedulerInstanceId()
						+ "] manually started.");
			} else {
				log.info("Scheduler [" + scheduler.getSchedulerInstanceId()
						+ "] already started.");
			}
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
	}

	private void stringToJobDataMap(JobDataMap map, String value) {
		if (value != null && !"".equals(value.trim())) {
			String[] kv = value.split(",");
			if (kv == null) {
				return;
			}
			for (String v : kv) {
				if (v != null && !"".equals(v) && v.indexOf("=") > 0) {
					String[] s = v.split("=");
					if (s == null || s.length == 0) {
						continue;
					}
					String vs = (s.length >= 2) ? s[1] : null;
					map.put(s[0], vs);
				}
			}
		}
	}

	/**
	 * <p>
	 * Trigger the identified <code>{@link org.quartz.JobDetail}</code> (execute
	 * it now) - the generated trigger will be non-volatile.
	 * </p>
	 */
	@Override
	public void triggerJob(String jobName, String groupName) {
		try {
			schedulerService.triggerJob(new JobKey(jobName, groupName));
		} catch (SchedulerException e) {
			throw newSystemException(e);
		}
	}

}
